
// pages/RedEnvelopes/redEnvelopes.js
const app = getApp()
// var base64 = require('../../utils/base64.js')
const CryptoJS = require('../../utils/aes-jia.js')
var timestamp = Date.parse(new Date()) / 1000; 
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    amountRedEnvelope:6.66,
    blessings:"",
    birthdayPerson:'',
    //生日id
    birthId:'',
    //生日人id
    relationId:'',
    amountLabel:6.66,
    isOver: true,
    user:{},
    walletBalance:'',
    userInfo:'',
    showPayPwdInput: false,  //是否展示密码输入层
    pwdVal: '',  //输入的密码
    payFocus: true, //文本框焦点
    prepaymentRecordId:'',
    whetherSetPayPwd:'',
    appoinbtnId:1,
    blessingsMb:[],
    blessingsnum:0,
    blessingsxg:false,
  },

  //输入金额
  amountInput:function (e) {
    e.detail.value = e.detail.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    e.detail.value = e.detail.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');

    if (e.detail.value.indexOf(".") < 0 && e.detail.value != "") {
      e.detail.value = parseFloat(e.detail.value);
    } else if (e.detail.value.indexOf(".") == 0) {
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "0.");
      e.detail.value = e.detail.value.replace(/\.{2,}/g, ".");
    }
    if (e.detail.value > 500000) {
      e.detail.value = 500000
    }
    this.setData({
      amountRedEnvelope: e.detail.value,
      amountLabel: e.detail.value
    })
    if (e.detail.value == 6.66){
      this.setData({
        appoinbtnId: 1,
      })
    } else if (e.detail.value == 11.11){
      this.setData({
        appoinbtnId: 2,
      })
    } else if (e.detail.value == 52.0){
      this.setData({
        appoinbtnId: 3,
      })
    }  else if (e.detail.value == 131.4) {
      this.setData({
        appoinbtnId: 4,
      })
    } else if (e.detail.value == 360) {
      this.setData({
        appoinbtnId: 5,
      })
    }else if (e.detail.value == 1001) {
      this.setData({
        appoinbtnId: 6,
      })
    }else{
      this.setData({
        appoinbtnId: 0,
      })
    }
    if (e.detail.value.length == 0) {
      this.setData({
        amountLabel: '0.00',
        appoinbtnId: 0,
      })
    }
  
  },
//选定金额
  appointBtn(e){
    var that = this
    var id = e.currentTarget.dataset.id
    var num = e.currentTarget.dataset.num
    if (id == that.data.appoinbtnId){
      that.setData({
        appoinbtnId: 0,
        amountLabel:'0.00',
        amountRedEnvelope:'',
      })
    }else{
      that.setData({
        appoinbtnId: id,
        amountRedEnvelope: num,
        amountLabel:num,
      })
    }
  },
//输入祝福语
  blessingInput:function(e) {
    if (e.detail.value.trim().length == 0) {
      this.setData({
        blessings: ''
      })
    } else {
      this.setData({
        blessings: e.detail.value,
        blessingsxg:true,
      })
    }
  },
//祝福语
  istemplateData() {
    var that = this
    app.req({
      url: "wechat/dictionary/listBydictType",
      method: "post",
      data: {
        dictType: "RED_BLESSINGS",
      },
      success: function (res) {
        if (200 == res.code) {
          console.log("祝福语", res)
          that.setData({
            blessingsMb: res.data,
            blessings: res.data[0].dictName
          })
        }
      }
    })
  },
  blessingsbtn(){
    var that = this
    var blessingsnum = that.data.blessingsnum + 1
    if (blessingsnum == that.data.blessingsMb.length) {
      blessingsnum = 0
    }
    if(that.data.blessingsxg){
      wx.showModal({
        content: '已编辑内容将会被替换，是否确认',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            that.setData({
              blessingsnum: blessingsnum,
              blessings: that.data.blessingsMb[blessingsnum].dictName,
              blessingsxg:false,
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      that.setData({
        blessingsnum: blessingsnum,
        blessings: that.data.blessingsMb[blessingsnum].dictName
      })
    }
  },
// 塞钱进空包
  payRedPacketsClcik:function(e) {
    var that = this;
    if (that.data.amountRedEnvelope == 0 || that.data.amountRedEnvelope.length == 0) {
      wx.showToast({
        title: "请输入红包金额",
        icon: 'none',
        duration: 2000
      })
      return
    } else if (that.data.blessings==''){
      that.setData({
        blessings: that.data.blessingsMb[0].dictName
      })
    }
    this.setData({
      show:true
    })
  },

//支付
  addToActivity1(e){
    var that = this;
    var payWay = e.currentTarget.dataset.id;
    if (payWay == 0) {
      if (that.data.walletBalance < that.data.amountRedEnvelope) {
        wx.showToast({
          title: "钱包余额不足",
          icon: 'none',
          duration: 2000
        })
        return
      } else {
        if (that.data.whetherSetPayPwd){
          that.setData({
            showPayPwdInput: true,
            payFocus:true,
          })
        }else{
          wx.showModal({
            title: '温馨提示',
            content: '为了您的账号安全，请设置支付密码',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                wx.navigateTo({
                  url: '/pages/password/password',
                })
              }
            }
          })
        }
      }
    }
  },
  addToActivity: function (e) {
    var that = this;
    var payWay = '';
    if (e == 0) {
     payWay=0
    }else{
     payWay = e.currentTarget.dataset.id;
    }
    if (that.data.isOver) {
      that.setData({
        isOver: false
      })
      var userId = that.data.user.id
      console.log("支付方式", payWay, app.globalData.url)
      var data = that.data;
      wx.request({
        url: app.globalData.url + "wechat/wxpay/sendRedEnvelope?uid=" + that.data.userInfo.id + '&prepaymentRecordId=' + that.data.prepaymentRecordId,
        method: "post",
        header: {
          'api-client': '8693ece21a2711ea995200163e05ff66',
          'api-version': '1.3.1',
        },
        showLoad: true,
        data: {
          birthId: that.data.birthId,
          sendId: userId,
          blessingType: 2,
          blessings: that.data.blessings,
          redPacket: that.data.amountRedEnvelope,
          relationId: that.data.relationId,
          payWay: payWay,
        },
        success: function (res) {
          console.log("支付", that.data.amountRedEnvelope, payWay,res)
          if (res.data.code == 200 && payWay == 0) {
            console.log("弹框", payWay)
            that.setData({
              show: false,
              isOver: true
            })
            wx.navigateBack({
              delta: 1
            })
            wx.showToast({
              title: "红包发送成功",
              duration: 2000
            })
          } else if (res.data.code == 200 && payWay == 1) {
            var paydata = res.data.data;
            console.log("调取", paydata)
            wx.requestPayment({
              timeStamp: paydata.prepayDate.timeStamp,
              nonceStr: paydata.prepayDate.nonceStr,
              package: 'prepay_id=' + paydata.prepayDate.prepay_id,
              signType: 'MD5',
              paySign: paydata.prepayDate.paySign,
              success(res) {
                that.setData({
                  outTradeNo: paydata.outTradeNo,
                  show: false,
                  isOver: true
                })
                wx.navigateBack({
                  delta: 1
                })
                wx.showToast({
                  title: "红包发送成功",
                  duration: 2000
                })
              },
              fail(res) {
                that.setData({
                  isOver: true
                })
                console.log("支付已取消")
                console.log(res.errMsg)
              }
            })
          } else {
            console.log('否则', payWay)
            that.setData({
              isOver: true
            })
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          }
        }
      });
    }
  },




  removePopContent:function(e) {
    this.setData({
      show: false
    })
  },

  //获取钱包余额
  getWalletBalance: function () {
    let that = this
    let data = {
      "pageNumber": 1,
      "pageSize": 10
    }
    app.req({
      url: "wechat/account/expenseCalendars",
      method: "post",
      data: data,
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            walletBalance: res.data.balance
          });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  //预支付
  operationRecord(){
    let that = this
    var payPwd = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.pwdVal)
    var amount = CryptoJS.EncryptBASE64(timestamp + '|' + that.data.amountRedEnvelope)
    console.log('预支付参数', payPwd, amount)
    app.req({
      url: "wechat/wxpay/operationRecord",
      method: "post",
      data: {
        payPwd: payPwd,
        amount: amount
      },
      success: function (res) {
        if (200 == res.code) {
          that.setData({
            prepaymentRecordId: res.msg,
            pwdVal:'',
          });
          console.log('预支付', that.data.prepaymentRecordId)
          that.addToActivity(0)
        } else {
          that.setData({
            pwdVal: '',
          });
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  // 支付密码
  /**
   * 隐藏支付密码输入层
   */
  hidePayLayer: function () {

    this.setData({
      pwdVal: '',
      showPayPwdInput: false,
      payFocus: false
    })

  },
  /**
   * 获取焦点
   */
  getFocus: function () {
    this.setData({ payFocus: true });
  },
  /**
   * 输入密码监听
   */
  inputPwd: function (e) {
    this.setData({ pwdVal: e.detail.value });
    if (this.data.pwdVal.length >= 6) {
      this.setData({
        showPayPwdInput: false,
        payFocus: false
      });
      this.operationRecord()
    }
  },
  // pswdBtn(){
  //   if (this.data.pwdVal.length >= 6) {
  //     this.setData({
  //       showPayPwdInput: false,
  //       payFocus: false
  //     });
  //     this.operationRecord()
  //   } else {
  //     wx.showToast({
  //       title: "请输入密码",
  //       icon: 'none',
  //       duration: 2000
  //     })
  //   }
  // },
  //获取是否有密码
  getIspswd() {
    var that = this
    app.req({
      url: 'wechat/user/whetherSetPayPwd',
      data: {
      },
      method: 'POST',
      success: function (res) {
        console.log('密码', res);
        if (res.code == 200) {
          that.setData({
            whetherSetPayPwd: res.data.whetherSetPayPwd
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that = this
    that.setData({
      birthdayPerson: options.birthdayPerson,
      birthId: options.birthId,
      relationId: options.relationId
    })
    app.getUserInfo(function (userInfo) {
      that.setData({
        user: userInfo
      })
      that.getWalletBalance()
    })
    that.istemplateData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    app.getUserInfo(function (userInfo) {
      that.setData({
        userInfo: userInfo
      })
      console.log('用户信息',userInfo)
    });
    that.getIspswd()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})